import React from 'react'
import View from 'lib/View.jsx'
import RootScope from './RootScope.es6'
import Card from 'lib/components/card.jsx'
import dispatcher from 'lib/dispatcher'
import TogglePanel from './TogglePanel.jsx'
import MultiCheckItem from './MultiCheckItem.jsx'
import cx from 'classnames'
import ChartWidget from 'lib/components/ChartWidget.jsx'
import UserAddedGrid from './UserAddedGrid.jsx'
import DateComparerPicker from '../common/DateComparerPicker.jsx'
import moment from 'moment'
import DeleableButtons from './DeleableButtons.jsx'
import _ from 'underscore'
import {Info} from 'lib/components/Notify.jsx';

class Card2 extends Card {
  constructor (props) {
    super(props);
    this.state = {
      showContent: true
    }
  }

  componentDidMount() {
    Info(
      <div>
        {BlueWare.isAndroid?(
          <p>
            探针版本更新至 3.0.0 版本以上可用
          </p>
        ):(
          <p>
            探针版本更新至 2.2.3 版本以上可用
          </p>
        )}
      </div>
    , {
      autoClose:false
    })
  }

  removeFilterHandler(target) {
    dispatcher.dispatch({
      $type: 'remove_filter',
      target
    })
  }

  redrawLineChart() {
    dispatcher.dispatch({
      $type: 'load_data'
    })
  }

  renderTitle() {
    return (
      <div className="widget-title">
        <div className="float-right">
          {
            <button
              className="btn-green btn-sm"
              onClick={this.redrawLineChart}>
              绘制筛选
            </button>
          }
          {
            this.props.useToggle ? (this.state.showContent ? (
              <a className="iconfont" href="javascript:;" onClick={this.slideUp.bind(this)}>&#xe611;</a>
            ) : (
              <a className="iconfont" href="javascript:;" onClick={this.slideDown.bind(this)}>&#xe610;</a>
            )) : null
          }
        </div>
        {
          <div>
            <h4>
              筛选条件：
              <DeleableButtons list={this.props.list} onClick={this.removeFilterHandler.bind(this)} />
            </h4>
          </div>
        }
      </div>
    )
  }
}

export default class RootView extends View {

  dayTypeChangeHandler (newType) {
    if(this.state.dayTypeState !== newType) {
      dispatcher.dispatch({
        $type: 'day_type_changed',
        newType: newType
      });
    }
  }

  componentDidMount() {
    super.componentDidMount();

    let versions = this.refs.versions;
    let channels = this.refs.channels;
    window.onresize = function () {
      let isChanged = false;
      let newState = {};

      if (this.lastVersionHeight !== versions.offsetHeight) {
        this.lastVersionHeight = versions.offsetHeight;
        newState.showVersionControlButton = this.lastVersionHeight > 34;
        isChanged = true;
      }

      if (this.lastChannelHeight !== channels.offsetHeight) {
        this.lastChannelHeight = channels.offsetHeight;
        newState.showChannelControlButton = this.lastChannelHeight > 34;

        isChanged = true;
      }

      if (isChanged) {
        this.setState(newState);
      }
    }.bind(this);

    setTimeout(window.onresize, 300);
  }

  componentWillUnmount() {
    window.onresize = null;

    super.componentWillUnmount();
  }

  render () {
    let versions = this.state.versions.map((item) => {
      return (<MultiCheckItem item={item} itemType={'id'} checkName="版本：" checkType={'version'} key={'user-addition-version-' + item.id}/>);
    });

    let channels = this.state.channels.map((item) => {
      return (<MultiCheckItem item={item} itemType={'name'} checkName="渠道：" checkType={'channel'} key={'user-addition-channel-' + item.id}/>);
    });

    let duration = this.state.duration();
    let days = duration.asDays();

    let exprotUrl = 'javascript:;';
    if (this.state.grid._originalData) {
      let dataSource = _.chain(this.state.grid._originalData)
      let first = dataSource.first().value();
      let last = dataSource.last().value();

      exprotUrl = BlueWare.urlPrefix + '/app/' + BlueWare.appId + '/useranalysis/useraddedexportxls';
      exprotUrl += '?timeUnit=' + this.state.dayTypeState;
      exprotUrl += '&startTime=' + (last ? last.startTime : moment().valueOf());
      exprotUrl += '&endTime=' + (first ? first.endTime : moment().valueOf());

      if (this.state.versionFilter) {
          exprotUrl += '&appVersionId=' + this.state.versionFilter;
      }

      if (this.state.channelFilter) {
        exprotUrl += '&channel=' + this.state.channelFilter;
      }
    }

    return (
      <div>
        <div className="float-position-relative">
          <div className="pure-g">
            <div className="pure-u-1">
              <div className="box">
                <Card2 title={'筛选条件'} list={this.state.filterList}>
                  <TogglePanel height={30} hidden={_.some(this.state.filterList, item => item.type === 'version')} showControlButton={this.state.showVersionControlButton}>
                    <div className="tabs-select" style={{'marginBottom': 0}}>
                      <div className="pure-g">
                        <div className="pure-u-3-24 pure-u-xl-1-12">
                          <h5 style={{'float': 'left', 'margin': '3px 10px auto'}}>版本：</h5>
                        </div>
                        <div ref="versions" className="pure-u-21-24 pure-u-xl-11-12">
                          <ul>
                            {versions}
                          </ul>
                        </div>
                      </div>
                    </div>
                  </TogglePanel>
                  <TogglePanel height={30} hidden={_.some(this.state.filterList, item => item.type === 'channel')} showControlButton={this.state.showChannelControlButton}>
                    <div ref="channels" className="tabs-select">
                      <div className="pure-g">
                        <div className="pure-u-3-24 pure-u-xl-1-12">
                          <h5 style={{'float': 'left', 'margin': '3px 10px auto'}}>渠道：</h5>
                        </div>
                        <div className="pure-u-21-24 pure-u-xl-11-12">
                          <ul>
                            {channels}
                          </ul>
                        </div>
                      </div>
                    </div>
                  </TogglePanel>
                </Card2>
              </div>
            </div>
          </div>
          <div className="pure-g">
            <div className="pure-u-1">
              <div className="box">
                <Card title={'新增用户趋势'} extra={
                    <div>
                      <DateComparerPicker
                        spanTime={duration.valueOf()}
                        displayText={this.state.comparerDisplayText}
                        style={{
                          float:'right',
                          marginLeft:'5px',
                          marginTop:'-7px'
                        }} />
                      <div className="switch-group" style={{marginTop:'0px'}}>
                        <button onClick={this.dayTypeChangeHandler.bind(this, 'daily')}
                           key="daily"
                           className={cx({active: this.state.dayTypeState === 'daily'})}
                           style={{
                             display: days >= 1 ? 'block' : 'none'
                           }}>
                           日
                        </button>
                        <button onClick={this.dayTypeChangeHandler.bind(this, 'weekly')}
                           key="weekly"
                           className={cx({
                             active: this.state.dayTypeState === 'weekly',
                             disabled: days < 7
                           })}
                           disabled={days < 7}
                           style={{
                             cursor: days < 7 ? 'not-allowed' : 'pointer'
                           }}>
                           周
                        </button>
                        <button onClick={this.dayTypeChangeHandler.bind(this, 'monthly')}
                           key="monthly"
                           className={cx({
                             active: this.state.dayTypeState === 'monthly',
                             disabled: days < 30
                           })}
                           disabled={days < 30}
                           style={{
                             cursor: days < 30 ? 'not-allowed' : 'pointer'
                           }}>
                           月
                        </button>
                      </div>
                    </div>
                }>
                  <ChartWidget store={this.state.chart0} tooltipShared={true} key={this.state.chart0Key}/>
                </Card>
              </div>
            </div>
          </div>
          <div className="pure-g">
            <div className="pure-u-1">
              <div className="box">
                <Card title={'新增用户明细'} extra={<a className="btn-blue" href={exprotUrl}>导出</a>}>
                  <UserAddedGrid store={this.state.grid} formatType={this.state.dayTypeState} />
                </Card>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

RootView.defaultProps = {
  Scope: RootScope
};
